//
//  CabinetCheckDetailController.m
//  YunGui
//
//  Created by Hanen 3G 01 on 16/3/23.
//  Copyright © 2016年 hanen. All rights reserved.
//

#import "CabinetCheckDetailController.h"
//#import "SettingButton.h"
#import "PictureSelectView.h"
#import "QBImagePickerController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "RuleViewController.h"
#import "CameraViewController.h"
#import "PopTipView.h"
#import "MySCrollView.h"
#import "SQButton.h"
#import "ShowPhotoViewController.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import "ShowPhotoViewController.h"

#define LocationTimeout 3  //   定位超时时间，可修改，最小2s
#define ReGeocodeTimeout 3 //   逆地理请求超时时间，可修改，最小2s
@interface CabinetCheckDetailController ()<QBImagePickerControllerDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextViewDelegate,PopTipViewDelegate,AMapLocationManagerDelegate>
{
    
    MySCrollView  *_scrollView;
    
    UIView   *_topView;//第一个视图
    
    UIView  *_secendView;//第二个视图
    
    CGFloat   space;
    
    CGFloat lastY;
    
//    SettingButton *_OKBtn;
//    SettingButton *_BadBtn;
//    
//    SettingButton *_lastBtn;//记录一个按钮

    UIView  *_thirdView;
    UILabel  *recordLabel;
    UITextView *writeRecodView;
//    UILabel *label;
    PopTipView *popViewGuiTi;//选择柜体
    PopTipView *popViewLocation;//开定位
    PopTipView *popViewCamera;//选择相机
    
    int   chooseFirst ;  //1.  先选择相机  2. 手机相册
    
    NSString *gps;
    NSString *gps_address;
//    NSString *longlatStr;
    NSDictionary *dataDict;
    
    CGFloat longStr;
    CGFloat latiStr;
    int gen;
    CLLocationManager *_cllocation;
    
    //将要检查的项目类型
    NSString *_beginCheckType;
    
    UIButton *chooseBtn;//定位的按钮
    UIButton *chooseGenBtn;//代数的按钮
}
@property (nonatomic, strong)  NSString *longlatStr;
@property (nonatomic, strong) AMapLocationManager *locationManager;

@property (nonatomic, copy) AMapLocatingCompletionBlock completionBlock;
@end

@implementation CabinetCheckDetailController
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = GrayBackColor;
    
    self.navigationItem.title = @"网点详情";
    self.navigationItem.leftBarButtonItem = [ViewTool getBackBarButtonItemWithTarget:self WithAction:@selector(backController)];
 
    space = [UIView getWidth:10.0f];

    longStr = 0;
    latiStr = 0;
    gen = -1;
//     self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(postCabinetCheck)];
    
        [self addScrollView];
    
    [self addSubviews];
    
    [self addSecendView];
 
//    [self addThirdView];
    
//    [self configLocationManager];
//    [self reGeocodeAction];
    [self loadDetailData];
}
- (void)addScrollView
{
    _scrollView = [[MySCrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64)];
    _scrollView.backgroundColor  = GrayBackColor;
    _scrollView.userInteractionEnabled = YES;
    [self.view addSubview:_scrollView];
}


- (void)loadDetailData
{
    NSMutableDictionary *dict;
    if(self.branchId){
    dict = [NSMutableDictionary dictionaryWithDictionary:@{@"method":@"app.branchCheck.detail",@"branch_id":self.branchId}];
    }
    //            [talkingArray removeAllObjects];
    NSDictionary *paramersDict = [DataTool addSignToDic:dict];
    [DataTool postWithUrl:HEAD_URL parameters:paramersDict success:^(id data) {
        id backData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments | NSJSONReadingMutableContainers error:nil];
        NSLog(@"柜体详情的数据%@",backData);
        dataDict = backData[@"data"];
        [self userData];
        
    } fail:^(NSError *error) {
        NSLog(@"%@",error.localizedDescription);
    }];
}

- (void)userData
{
    for (int i = 0; i< 5; i++) {
        UILabel *contentLabel = [_topView viewWithTag:531 + i];
        if (i == 0) {
            contentLabel.text = dataDict[@"base"][@"branch_no"];
        }
        if (i == 1) {
            contentLabel.text = dataDict[@"base"][@"branch_name"];
        }
        if (i == 2) {
            contentLabel.text = dataDict[@"base"][@"complex"];
        }
        if (i == 3) {
            contentLabel.text = dataDict[@"check"][@"checked_at"];
        }
        if (i == 4) {
            contentLabel.text = dataDict[@"base"][@"address"];
        }
        
    }
    NSArray *typeCheckArray = dataDict[@"check_detail"];
    for (int i = 0; i < typeCheckArray.count; i ++) {
        UIButton *btn = [_secendView viewWithTag:10086 + i];
        NSString *str;
        if ([typeCheckArray[i][@"status"] intValue] == 1 ) {
            str = @"合格";
        }else if ([typeCheckArray[i][@"status"] intValue] == 2 ) {
            str = @"不合格";
            self.typeNum = [NSNumber numberWithInt:[typeCheckArray[i][@"type"] intValue]];
        }else {
            str = @"待检查";
            self.typeNum = [NSNumber numberWithInt:[typeCheckArray[i][@"type"] intValue]];
        }
        NSLog(@"%@",self.typeNum);
        [btn setTitle:str forState:UIControlStateNormal];
    }
    
    if(![dataDict[@"check"][@"longitude"] isEqualToString:@""] && ![dataDict[@"check"][@"latitude"] isEqualToString:@""] && dataDict[@"check"][@"longitude"] != nil  && dataDict[@"check"][@"longitude"] != nil)
    {
        UILabel *conteL = [_topView viewWithTag:531 + 5];
        conteL.text = [NSString stringWithFormat:@"%@,%@",dataDict[@"check"][@"longitude"],dataDict[@"check"][@"latitude"]];
        conteL.textColor = UIColorFromRGB(0xf35d51);
        longStr = [dataDict[@"check"][@"longitude"] floatValue];
        latiStr = [dataDict[@"check"][@"latitude"] floatValue];
    }else{
        [self configLocationManager];
        [self reGeocodeAction];
    }
    if (dataDict[@"check"][@"gen"] != nil && ![dataDict[@"check"][@"gen"] isEqualToString:@""]) {
        chooseGenBtn.userInteractionEnabled = NO;
        UILabel *conteL = [_topView viewWithTag:531 + 6];
       int i  =[ dataDict[@"check"][@"gen"] intValue];
        if (i == 0 ) {
            conteL.text = @"三代";
            gen=0;
        }else{
            gen=1;
         conteL.text = @"五代";
        }
        conteL.textColor = UIColorFromRGB(0xfac502);
    }else{
        chooseGenBtn.userInteractionEnabled = YES;
        gen=-1;
        [self chooseGuiTiNum];
    }
//    if (dataDict[@"data"][@"check"][@"gen"]) {
//        
//    }
//    

}
- (void)addSubviews
{
    _topView = [[UIView alloc] initWithFrame:CGRectMake(0, space + 3, kScreenWidth, [UIView getHeight:200.0f])];
    _topView.backgroundColor = [UIColor whiteColor];
    
    [_scrollView addSubview:_topView];
    
    UIView *line1 = [ViewTool getLineViewWith:CGRectMake(0, 0, kScreenWidth, 1) withBackgroudColor:GRAYLINECOLOR];
    [_topView addSubview:line1];
    
    CGFloat  imagew = 22.0f;
    
    UIImageView *infoImage = [[UIImageView alloc] initWithFrame:CGRectMake(2 * space,line1.maxY + space, imagew, imagew)];
    infoImage.image = [UIImage imageNamed:@"Btn_Normal_Xinxi"];
//      [infoImage sd_setImageWithURL:[NSURL URLWithString:@"http://test.yun-gui.com/tools/show?path=./uploads/20150513/143151429747836.jpg"] placeholderImage:nil];
//    infoImage.backgroundColor = BlueColor;
//    infoImage.layer.cornerRadius = infoImage.width / 2.0f;
//    infoImage.layer.masksToBounds = YES;
    [_topView addSubview:infoImage];
    
    UILabel  *infoLabel = [ViewTool getLabelWith:CGRectMake(infoImage.maxX +1.5 * space, infoImage.y, 150.0f, [UIView getHeight:18.0f]) WithTitle:@"基本信息" WithFontSize:15.0f WithTitleColor:BLACKCOLOR WithTextAlignment:NSTextAlignmentLeft];
    [_topView addSubview:infoLabel];
    
    
    UIView *line2 = [ViewTool getLineViewWith:CGRectMake(infoLabel.x, infoLabel.maxY + space, kScreenWidth - infoLabel.x, 1) withBackgroudColor:GRAYLINECOLOR];
    [_topView addSubview:line2];
    
    NSArray * titleArra = @[@"网点编号",@"网点名称",@"所在小区",@"检查时间",@"安装地址",@"百度坐标",@"柜体代数"];
    CGFloat labelH = 20.0f;
    CGFloat labelW = 70.0f;
    
    for (int i = 0; i<titleArra.count ; i++) {
        UILabel *label = [ViewTool getLabelWith:CGRectMake(line2.x, line2.maxY + space +(space / 2.0f + labelH) * i, labelW, labelH) WithTitle:titleArra[i] WithFontSize:14.0f WithTitleColor:UIColorFromRGB(0xa0a3a5) WithTextAlignment:NSTextAlignmentLeft];
//        label.backgroundColor = BlueColor;
        [_topView addSubview:label];
        
        UILabel  *contentLabel = [ViewTool getLabelWith:CGRectMake(label.maxX + space / 2.0f ,  label.y,  kScreenWidth - label.maxX - 2 * space,labelH) WithTitle:@" " WithFontSize:16.0f WithTitleColor:BLACKCOLOR WithTextAlignment:NSTextAlignmentLeft];
            //        contentLabel.backgroundColor = BlueColor;
            [_topView addSubview:contentLabel];
               contentLabel.tag = 531 + i;
        if (i == titleArra.count -2) {
            
            CGRect frame = contentLabel.frame;
            frame.size.width = kScreenWidth - label.maxX - 40;
            contentLabel.frame = frame;
            
            chooseBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth - 40, label.y, 25.0f, 25.0f)];
            //            btn.backgroundColor = [UIColor redColor];
            [chooseBtn setBackgroundImage:[UIImage imageNamed:@"zuobiao.png"] forState:UIControlStateNormal];
            [chooseBtn addTarget:self action:@selector(Localization) forControlEvents:UIControlEventTouchUpInside];
            [_topView addSubview:chooseBtn];
            
        }

        if (i == titleArra.count - 1) {
            chooseGenBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth - 40, label.y, 25.0f, 25.0f)];
            //            btn.backgroundColor = [UIColor redColor];
            [chooseGenBtn setBackgroundImage:[UIImage imageNamed:@"guiti"] forState:UIControlStateNormal];
            if (gen == -1) {
                [chooseGenBtn addTarget:self action:@selector(chooseGuiTiNum) forControlEvents:UIControlEventTouchUpInside];
            }
            
            [_topView addSubview:chooseGenBtn];
            contentLabel.textColor = UIColorFromRGB(0xfac502);
            lastY = contentLabel.maxY;
            if (self.staus == 1 || self.staus == 2) {
                if (dataDict) {
                    if ([dataDict[@"check"][@"gen"] intValue] == 0) {
                        contentLabel.text = @"三代";
                        gen = 1;
                    }else if([dataDict[@"check"][@"gen"] intValue] == 1){
                        gen = 2;
                        contentLabel.text = @"五代";
                    }
                    chooseGenBtn.enabled = NO;
                }
               
            }
            
           
        }
//        NSLog(@"%@---%@",NSStringFromCGRect(label.frame),NSStringFromCGRect(contentLabel.frame));
    }
        
    
    
    UIView *line3 = [ViewTool getLineViewWith:CGRectMake(0, lastY + 3 * space, kScreenWidth, 1) withBackgroudColor:GRAYLINECOLOR];
    [_topView addSubview:line3];
     _topView.frame = CGRectMake(0, space + 3, kScreenWidth, line3.maxY);
    [self configLocationManager];
    [self reGeocodeAction];
//      NSLog(@"11  --%f",_topView.height);
}
#pragma mark --点击百度坐标的方法
- (void)Localization
{  
    if ([CLLocationManager locationServicesEnabled] &&
        ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized
         || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined)) {
            //定位功能可用，开始定位
//            _cllocation = [[CLLocationManager alloc] init];
//            _cllocation.delegate = self;
//            [locationManger startUpdatingLocation];
//            if(longStr != 0 && latiStr != 0){
                [self configLocationManager];
                [self reGeocodeAction];
//            }
        }
    else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied){
//        NSlog("定位功能不可用，提示用户或忽略");
//        popViewGuiTi= [[PopTipView alloc] initWithFrame:CGRectMake(0, 0, [UIView getWidth:250.0f], [UIView getHeight:120.0f])];
//        popViewGuiTi.center = self.view.center;
//        popViewGuiTi.delegate = self;
//        popViewGuiTi.tipsLabel.text = @"提示:您未开启定位，请尝试开启定位。";
////        popViewGuiTi.lefttext = @"三代";
////        popViewGuiTi.righText = @"五代";
//        popViewLocation.lefttext = @"确定";
//        popViewLocation.rightBtn.hidden = YES;
////        popViewGuiTi.isShowImage = YES;
//        popViewGuiTi.delegate = self;
//        [popViewGuiTi showToView:self.view];
        [Tools showMessage:@"提示:您未开启定位，请尝试开启定位。" view:self];
    }
}
- (void)chooseGuiTiNum
{
    _scrollView.delaysContentTouches = YES;
    _scrollView.canCancelContentTouches = NO;
    popViewGuiTi= [[PopTipView alloc] initWithFrame:CGRectMake(0, 0, [UIView getWidth:250.0f], [UIView getHeight:130.0f])];
    popViewGuiTi.center = CGPointMake(kScreenWidth / 2.0f, kScreenHeight / 2.0f);
    popViewGuiTi.delegate = self;
    popViewGuiTi.tipsLabel.text = @"请选择您检查的机柜为几代?";
    popViewGuiTi.lefttext = @"三代";
    popViewGuiTi.righText = @"五代";
    popViewGuiTi.delegate = self;
    popViewGuiTi.isShowImage = YES;
    [popViewGuiTi showToView:self.view];
}
- (void)clickLeftbtnWith:(PopTipView *)popView{
    UILabel *lastLab = [_topView viewWithTag:531 + 6];
    if (popView == popViewGuiTi) {
        popViewGuiTi.changeIndex = 1;//改变index为1的 按钮的点击颜色
        lastLab.text = @"三代";
        
        lastLab.textColor = UIColorFromRGB(0xfac502);
        gen = 0;
        [self performSelector:@selector(delayDismiss) withObject:nil afterDelay:0.8];
        
    }else if(popViewCamera == popView){
        [popViewCamera dimiss];
        chooseFirst = 1;
        
        if(![Tools isAllowTakePhoto]){
            [Tools showMessage:@"APP无相机访问权限，请先设置!" view:self];
            return;
        }
        CameraViewController *cameraVC = [[CameraViewController alloc] init];
        [self presentViewController:cameraVC animated:YES completion:nil];
    }else if(popViewLocation == popView){
        [popViewLocation dimiss];
    }
}
- (void)delayDismiss
{
     [popViewGuiTi dimiss];
}
- (void)clickRightbtnWith:(PopTipView *)popView{
    UILabel *lastLab = [_topView viewWithTag:531 + 6];
    if (popView == popViewGuiTi) {
        popViewGuiTi.changeIndex = 2;
        gen = 1;
        lastLab.text = @"五代";
        lastLab.textColor = UIColorFromRGB(0xfac502);
        [self performSelector:@selector(delayDismiss) withObject:nil afterDelay:0.8];
    }else if(popViewCamera == popView){
        chooseFirst = 2;
        [self takePictureInPhone1];
    }
}


#pragma mark - Action Handle

- (void)configLocationManager
{
    self.locationManager = [[AMapLocationManager alloc] init];
    
    [self.locationManager setDelegate:self];
    
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    
    [self.locationManager setPausesLocationUpdatesAutomatically:NO];
    
    [self.locationManager setAllowsBackgroundLocationUpdates:NO];
    
//    [self.locationManager setLocationTimeout:LocationTimeout];
//    
//    [self.locationManager setReGeocodeTimeout:ReGeocodeTimeout];
    
}

- (void)cleanUpAction
{
    [self.locationManager stopUpdatingLocation];
    
    [self.locationManager setDelegate:nil];
}

- (void)reGeocodeAction
{
    [self.locationManager startUpdatingLocation];
//    [self.locationManager requestLocationWithReGeocode:YES completionBlock:self.completionBlock];
}
- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error
{
    //定位错误
    NSLog(@"%s, amapLocationManager = %@, error = %@", __func__, [manager class], error);
}
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location
{
    //定位结果
    NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
//    gps_address = regeocode.formattedAddress;
    gps = [NSString stringWithFormat:@"%f,%f",location.coordinate.longitude,location.coordinate.latitude];
    
//    NSLog(@"%@",[NSString stringWithFormat:@"%@ \n %@-%@-%.2fm", regeocode.formattedAddress,regeocode.citycode, regeocode.adcode, location.horizontalAccuracy]);
    NSLog(@"%@",[NSString stringWithFormat:@"lat:%f;lon:%f \n accuracy:%.2fm", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy]);
    longStr = location.coordinate.longitude;
    latiStr = location.coordinate.latitude;
   _longlatStr = [NSString stringWithFormat:@"%f,%f",location.coordinate.longitude,location.coordinate.latitude];
    
    UILabel *conten = [_topView viewWithTag:531 + 5];
    if(conten){
    conten.text = _longlatStr;
    conten.textColor = UIColorFromRGB(0xf35d51);
    
    }
    if (location && conten) {
         [self cleanUpAction];
    }
  
}

- (void)addSecendView
{
//    NSLog(@"%f",_topView.maxY);
    _secendView = [[UIView alloc] initWithFrame:CGRectMake(0, _topView.maxY + space +3, kScreenWidth , 160.0f)];
    _secendView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:_secendView];
    
    
    UIView *line1 = [ViewTool getLineViewWith:CGRectMake(0, 0, kScreenWidth, 1) withBackgroudColor:GRAYLINECOLOR];
    [_secendView addSubview:line1];
    
    
    CGFloat  imagew = 22.0f;
    
    UIImageView *findImage = [[UIImageView alloc] initWithFrame:CGRectMake(2 * space,line1.maxY + space, imagew, imagew)];
   
    findImage.image = [UIImage imageNamed:@"Btn_Normal_Yanshou"];
//    findImage.backgroundColor = BlueColor;
//    findImage.layer.cornerRadius = findImage.width / 2.0f;
//    findImage.layer.masksToBounds = YES;
    [_secendView addSubview:findImage];
    
    UILabel  *findLabel = [ViewTool getLabelWith:CGRectMake(findImage.maxX +1.5 * space, findImage.y, 80.0f, [UIView getHeight:18.0f]) WithTitle:@"项目检查" WithFontSize:15.0f WithTitleColor:BLACKCOLOR WithTextAlignment:NSTextAlignmentLeft];
    [_secendView addSubview:findLabel];
    
    UIView *lineView1 = [ViewTool getLineViewWith:CGRectMake(findLabel.x, findLabel.maxY + space + 3, kScreenWidth - findLabel.x, 1) withBackgroudColor:GRAYLINECOLOR];
    [_secendView addSubview:lineView1];
    CGFloat sectionH = 50.0f;
//    NSArray *arr = @[@"NO.01",@"NO.02",@"NO.03"];
    NSArray *arr2 = @[@"雨棚",@"地坪",@"柜体"];
    for (int i = 0; i< 3; i++) {
//        UILabel *numLabel = [ViewTool getLabelWith:CGRectMake(lineView1.x,  lineView1.maxY + 2 * space + (20.0f + sectionH) * i, 60.0f, 20.0f) WithTitle:arr2[i] WithFontSize:14.0f WithTitleColor:GRAYCOLOR WithTextAlignment:NSTextAlignmentLeft];
//        numLabel.backgroundColor = BlueColor;
//        [_secendView addSubview:numLabel];
        
        UILabel *typeLabel = [ViewTool getLabelWith:CGRectMake(lineView1.x +40.0f + 30.0f,  lineView1.maxY + 2 * space + (20.0f + sectionH) * i, 60.0f, 20.0f) WithTitle:arr2[i] WithFontSize:15.0f WithTitleColor:BLACKCOLOR WithTextAlignment:NSTextAlignmentLeft];
        [_secendView addSubview:typeLabel];
        
//        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(typeLabel.maxX + 5, typeLabel.y, 20.0f, 20.0f)];
//        btn.backgroundColor = [UIColor orangeColor];
//        [btn addTarget:self action:@selector(clickToJumpRule:) forControlEvents:UIControlEventTouchUpInside];
//        [_secendView addSubview:btn];
        
        UIButton *btn2 = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth - 70.0f - 20.0f, typeLabel.centerY - 20.0f, 70.0f, 40.0f)];
//        btn2.backgroundColor = [UIColor redColor];
        btn2.tag = 10086 + i;
        [btn2 setTitle:@"待检查" forState:UIControlStateNormal];
        [btn2 setTitleColor:GRAYCOLOR forState:UIControlStateNormal];
        btn2.titleLabel.font = [ViewTool getFont:15.0f];
//        [btn2 addTarget:self action:@selector(clickToChoosePic:) forControlEvents:UIControlEventTouchUpInside];
        [_secendView addSubview:btn2];
        CGFloat linew;
        if(i != 2){
            linew = kScreenWidth - typeLabel.x;
        }else{
            linew = kScreenWidth;
        }
        UIView *lineee = [ViewTool getLineViewWith:CGRectMake(typeLabel.x, typeLabel.maxY  + 20.0f, linew, 1) withBackgroudColor:GRAYLINECOLOR];
        [_secendView addSubview:lineee];
        
        if (i == 2) {
            _secendView.frame =  CGRectMake(0, _topView.maxY + space +3, kScreenWidth ,lineee.maxY);
            lineee.frame = CGRectMake(0, typeLabel.maxY  + 20.0f, kScreenWidth ,1);
        }
        
    }
    
//    _scrollView.contentSize = CGSizeMake(kScreenWidth, _secendView.maxY + 10);
    
    UIButton *beginBtn =[[UIButton alloc] initWithFrame:CGRectMake(0, 0, [UIView getWidth:300.0f], [UIView getWidth:45.0f])];
    beginBtn.center = CGPointMake(kScreenWidth / 2.0f , _secendView.maxY + 70.0f);
    if (self.isCheckOK) {
        [beginBtn setTitle:@"完成检查" forState:UIControlStateNormal];
    }else{
        [beginBtn setTitle:@"开始检查" forState:UIControlStateNormal];
    }
    
    [beginBtn addTarget:self action:@selector(clickBegin) forControlEvents:UIControlEventTouchUpInside];
    beginBtn.backgroundColor = BlueColor;
//    [beginBtn setTitle:@"开始检查" forState:UIControlStateNormal];
//    [beginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    beginBtn.titleLabel.font = [UIFont systemFontOfSize:16.0f];
//    [beginBtn setBackgroundImage:[UIImage imageNamed:@"anniu .png"] forState:UIControlStateNormal];
//    [beginBtn setBackgroundImage:[UIImage imageNamed:@"Btn_Push_Denglu.png"] forState:UIControlStateHighlighted];
//    beginBtn.backgroundColor = BlueColor;
    [_scrollView addSubview:beginBtn];
    
    _scrollView.contentSize = CGSizeMake(kScreenWidth, beginBtn.maxY + 20.0);
}
#pragma mark --    //开始检查
 -(void)clickBegin
{
    
    if (self.isCheckOK) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
    if (gen == -1) {
        [Tools showMessage:@"请选择柜体代数" view:self];
    }else if(longStr == 0 || latiStr == 0){
         [Tools showMessage:@"提示:请先定位。" view:self];
    }else{
//开始检查
        NSLog(@"代数%d",gen);
    NSInteger str = [[NSUserDefaults standardUserDefaults] integerForKey:@"userId"];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:@{@"method":@"app.branchCheck.start.check",@"branch_id":self.branchId,@"longitude": @(longStr),@"latitude":@(latiStr),@"gen":@(gen),@"check_user_id" : @(str)}];
  
    NSDictionary *paramersDict = [DataTool addSignToDic:dict];
        NSLog(@"开始检查的参数 %@",paramersDict);
    [DataTool postWithUrl:HEAD_URL parameters:paramersDict success:^(id data) {
        id backData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments | NSJSONReadingMutableContainers error:nil];
        NSLog(@"开始检查的数据%@",backData);
        if ([backData[@"status"] isEqualToString:@"ERROR"]) {

            int code = [[(NSDictionary *)backData objectForKey:@"code"] intValue];
            NSString *msg = [(NSDictionary *)backData objectForKey:@"msg"];
            NSLog(@"%d%@",code,msg);
            [Tools showMessage:msg view:self];
            return ;
        }
        //这些存储一下 到评定结果中获取
        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:@{@"branch_id":self.branchId,@"longitude": @(longStr),@"latitude":@(latiStr),@"gen":@(gen),@"check_user_id" : @(str),@"type" : backData[@"data"][@"next_type"],@"branch_name" : dataDict[@"base"][@"branch_name"],@"check_at" : dataDict[@"check"][@"checked_at"],@"address" :  dataDict[@"base"][@"address"],@"check_id" :dataDict[@"check"][@"check_id"],@"branch_NO" : dataDict[@"base"][@"branch_no"]}];
        
        
        [[NSUserDefaults standardUserDefaults] setObject:dict forKey:@"checkDict"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        if (backData[@"data"][@"check_id"]) {
            RuleViewController * cv = [[RuleViewController alloc] init];//wwrr
            cv.ruleType = backData[@"data"][@"next_type"];
//            cv.ruleType = self.typeNum;
            cv.check_id = backData[@"data"][@"check_id"];
            cv.inCameraChoose = NO;
            cv.branach_Id = self.branchId;
            cv.branch_no = dataDict[@"base"][@"branch_no"];
            cv.branach_name = dataDict[@"base"][@"branch_name"];
            [self.navigationController pushViewController:cv animated:YES];
        }
      
        
    } fail:^(NSError *error) {
        NSLog(@"%@",error.localizedDescription);
    }];
      }
    }
//#warning 暂时测试
//    RuleViewController * cv = [[RuleViewController alloc] init];//wwrr
//    [self.navigationController pushViewController:cv animated:YES];
    
}

- (void)textViewDidBeginEditing:(UITextView *)textView{
  
    if (recordLabel.hidden == NO) {
        [UIView animateWithDuration:0.1 animations:^{
            recordLabel.hidden = YES;
        }];
    }
}

- (void)textViewDidChange:(UITextView *)textView{
    if (textView.text.length == 0 || [textView.text isEqualToString:@""]) {
        if (recordLabel.hidden == YES) {
            [UIView animateWithDuration:0.1 animations:^{
                recordLabel.hidden = NO;
            }];
            writeRecodView.text = @"";
        }
    }
}
#pragma mark --点击添加照片

- (void)takePictureInPhone1
{
    if(![Tools isAllowTakePhoto]){
        [Tools showMessage:@"APP无相机访问权限，请先设置!" view:self];
        return;
    }
    
    if (![QBImagePickerController isAccessible]) {
        [Tools showMessage:@"相机不可用哦" view:self];
    }
    QBImagePickerController *imagePickerController = [[QBImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsMultipleSelection = YES;
    imagePickerController.maximumNumberOfSelection = 20;//最大上传5张
    
    UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:imagePickerController];
    [self presentViewController:navigationController animated:YES completion:NULL];
}
- (void)backController
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
//       [self loadDetailData];
//    if ( self.staus == 0 && self.isFirst) {
//        //
//        [self chooseGuiTiNum];
//    }
    NSArray *controlleArr = self.navigationController.viewControllers;
    for (UIViewController *controll in controlleArr) {
        if ([controll isKindOfClass:[ShowPhotoViewController class]]) {
            [controll removeFromParentViewController];
        }
    }
    if(self.BackDict){
        
    }
    
    if(_isRefresh){
    }
}
- (void)viewDidDisappear:(BOOL)animated
{
    self.isFirst = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0) {
        //需要注意的是self.isViewLoaded是必不可少的，其他方式访问视图会导致它加载，在WWDC视频也忽视这一点。
        if (self.isViewLoaded && !self.view.window)// 是否是正在使用的视图
        {
            // Add code to preserve data stored in the views that might be
            // needed later.
            // Add code to clean up other strong references to the view in
            // the view hierarchy.
            self.view = nil;// 目的是再次进入时能够重新加载调用viewDidLoad函数。
        }
    }
    dispatch_async(
                   dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
                   , ^{
                       NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
                       
                       NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
//                       NSLog(@"files :%d",[files count]);
                       for (NSString *p in files) {
                           NSError *error;
                           NSString *path = [cachPath stringByAppendingPathComponent:p];
                           if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                               [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                           }
                       };});
    
    [[SDImageCache sharedImageCache] clearDisk];//清理磁盘
    // Dispose of any resources that can be recreated.
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    _locationManager = nil;
    _secendView = nil;
    _thirdView = nil;
    _topView = nil;
    dataDict = nil;
}
@end

